package cn.summit.serialization.adapter;

import cn.summit.tools.DateUtils;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

/**
 * @author summit
 * @since 2020/11/13 14:03
 */
public class DateTimeAdapter extends TypeAdapter<LocalDateTime> {

    public static final DateTimeFormatter FORMATTER = DateUtils.DATE_TIME_FORMATTER;

    @Override
    public void write(JsonWriter out, LocalDateTime value) throws IOException {
        if (value == null) {
            out.nullValue();
        } else {
            out.value(value.format(FORMATTER));
        }
    }

    @Override
    public LocalDateTime read(JsonReader in) throws IOException {
        if (in.peek() == JsonToken.NULL) {
            in.nextNull();
            return null;
        } else {
            String str = in.nextString();
            if (StringUtils.isBlank(str)) {
                return null;
            }
            return LocalDateTime.parse(str, FORMATTER);
        }
    }
}

